import { createApp } from 'vue'
import './style.css'
import './animate.less'
import router from './router/index'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { createPinia } from 'pinia'
import { NoticeBar } from 'vant';
import App from './App.vue'
import DragButton from './components/canvas/DragButton.vue'
import DragText from './components/canvas/DragText.vue'
import DragRect from './components/canvas/DragRect.vue'
import DragEchart from './components/canvas/DragEchart.vue'
import DragImg from './components/canvas/DragImg.vue'
import { userToolbarStore } from './store/index.js'


import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 全局注册组件
app.component("drag-button", DragButton)
app.component("drag-text", DragText)
app.component("drag-rect", DragRect)
app.component("drag-echart", DragEchart)
app.component("drag-img", DragImg)

// 裂图自定义指令
app.directive("error", {
  mounted(el, { value }) {
    const imgHtml = document.createElement("img")
    imgHtml.src = value
    imgHtml.onload = () => {
      el.src = value
    };

    imgHtml.onerror = () => {
      el.src = "https://pic4.zhimg.com/50/v2-3d93dd2a217a09fc9d699d9d7d173707_hd.jpg"
    }
  }
})

// 拖拽自定义指令
app.directive("drag", {
  mounted(el, { value }) {
    // 添加鼠标按下事件
    el.addEventListener('mousedown', function () {
      const currentItem = userToolbarStore().componentsList.find(item => item.id === value)
      // console.log("按下事件", currentItem)
      const moveFn = (event) => {
        currentItem ? currentItem.style.left = event.clientX - 260 : ''
        currentItem ? currentItem.style.top = event.clientY - 100 : ''
      }
      document.addEventListener('mousemove', moveFn)

      el.addEventListener('mouseup', function () {
        // 往撤销数组中添加数据
        userToolbarStore().addBackOut(currentItem)
        document.removeEventListener("mousemove", moveFn)
      })
    })
  }
})

app.use(NoticeBar);
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')